package com.ychen.ruijee.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.org.apache.xpath.internal.operations.Or;
import com.ychen.ruijee.bean.*;
import com.ychen.ruijee.common.BaseContext;
import com.ychen.ruijee.common.R;
import com.ychen.ruijee.dao.*;
import com.ychen.ruijee.service.AddressBookService;
import com.ychen.ruijee.service.OrderService;
import com.ychen.ruijee.service.ShoppingCartService;
import com.ychen.ruijee.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.annotation.security.DeclareRoles;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author ychen@gotop.cn
 * @date 2024-06-08 23:30
 */
@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderDao, Orders> implements OrderService {

    @Resource
    private UserDao userDao;

    @Resource
    private ShoppingCartDao shoppingCartDao;

    @Resource
    private OrderDetailDao orderDetailDao;

    @Resource
    private AddressBookDao addressBookDao;


    /**
     * 下单
     * @param orders
     * @return
     */
    @Override
    @Transactional
    public boolean submitOrder(Orders orders) {
        log.info("【下单数据 为】：{}",orders.toString());
        Long userId = BaseContext.getCurrentId();
        // 查询 购物车信息
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartDao.selectList(wrapper);
        if (shoppingCarts == null || shoppingCarts.size() == 0){
            // 优化 使用全局异常处理
            return  false;
        }
        // 查询 用户信息
        User user = userDao.selectById(userId);
        if (user == null){
            return false;
        }
        // 查询地址数据
        AddressBook addressBook = addressBookDao.selectById(orders.getAddressBookId());
        if(addressBook == null){
            log.error("addressBook 对象为 null ");
            return false;
        }

        // 使用 mybatisPlus 的idworker 生成订单号
        long orderId = IdWorker.getId();
        // 使用 原子类 声明总金额 保证了 并发下 数据的安全
        AtomicInteger sumAmout = new AtomicInteger(0);

        // 4.1 将订单保存到 order_detail 表中,shoppingCart ——> orderDetail
        shoppingCarts.stream().forEach((item)->{
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(item,orderDetail,"id");
            orderDetail.setOrderId(orderId);
            // 计算总金额
            sumAmout.addAndGet((item.getAmount().multiply(new BigDecimal(item.getNumber()))).intValue());
            // 保存到 orderDetail　表中
            orderDetailDao.insert(orderDetail);
        });
        // 4.2 保存 信息到 order表中
        orders.setUserId(userId);
        // 订单号
        orders.setNumber(UUID.randomUUID().toString());
        orders.setStatus(2);
        orders.setAddressBookId(addressBook.getId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setAmount(new BigDecimal(sumAmout.get()));
        orders.setPhone(user.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());

        log.info("【》>>>>>>>》orders】中的信息为 {}",orders );
        boolean saveFlag = this.save(orders);
        // 情况 购物车中的数据

        shoppingCartDao.delete(wrapper);
         return saveFlag;
    }

    /**
     * 订单分页查询展示
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page<Orders> pageInfOrder(Integer page, Integer pageSize) {
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        Long currentId = BaseContext.getCurrentId();
        wrapper.eq(Orders::getUserId,currentId);
        this.page(pageInfo,wrapper);

        return pageInfo;
    }
}
